<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="仓库" prop="depotId">
        <el-select v-model="queryParams.depotId"  placeholder="请选择仓库" filterable clearable>
          <el-option
            v-for="item in allDepot1"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="物品" prop="inventoryId">
        <el-select v-model="queryParams.inventoryId" placeholder="请选择物品" filterable clearable>
          <el-option
            v-for="item in selectAllInventory"
            :key="item.id"
            :label="item.firstLetter + ' - ' + item.label"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['warehouse:OutRyDepotItem:add']"
        >新增</el-button>
      </el-col>

<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['warehouse:OutRyDepotItem:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['warehouse:OutRyDepotItem:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="OutRyDepotItemList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键" align="center" prop="id" />-->
<!--      <el-table-column label="商品Id" align="center" prop="inventoryId" />-->

      <el-table-column label="仓库" align="center" prop="depotName" />
      <el-table-column label="商品首字母" align="center" prop="firstLetter"/>
      <el-table-column label="商品" align="center" prop="inventoryName" />
      <el-table-column label="规格" align="center" prop="specifications" />
      <el-table-column label="项目名称" align="center" prop="projectName"/>
      <el-table-column label="项目编号" align="center" prop="projectCode"/>
      <el-table-column label="出库数量" align="center" prop="operNumber" />
      <el-table-column label="金额" align="center" prop="allPrice" />
      <el-table-column label="当前库存" align="center" prop="currentNumber" />
      <el-table-column label="出库时间" align="center" prop="operTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" align="center" prop="headerType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ware_depot_item_type" :value="scope.row.headerType"/>
        </template>
      </el-table-column>

      <el-table-column label="修改时间" align="center" prop="updateTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['warehouse:OutRyDepotItem:edit']"
          >修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加出库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="仓库" prop="depotId">
          <!--          <el-input v-model="form.depotId" placeholder="请输入仓库ID" />-->
          <el-select v-model="form.depotId"  @change="onSelectallRyInventory" placeholder="请选择仓库" filterable>
            <el-option
              v-for="item in allDepot"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出库物品" prop="inventoryId">
          <!--          <el-input v-model="form.inventoryId" placeholder="请输入商品Id" />-->
          <el-select v-model="form.inventoryId" @change="onSelectedInventory" placeholder="请选择出库物品" filterable>
            <el-option
              v-for="item in allInventory"
              :key="item.inventoryId"
              :label="item.inventFirstLetter + ' - ' + item.inventoryName"
              :value="item.inventoryId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目代号" prop="projectCode">
          <!--          <el-input v-model="form.inventoryId" placeholder="请输入商品Id" />-->
          <el-select v-model="form.headerId" placeholder="请选择项目" filterable clearable>
            <el-option
              v-for="item in linkHeadOptions"
              :key="item.id"
              :label="item.projectCode"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品规格" prop="specifications">
          <el-input v-model="form.specifications" :disabled="true"/>
        </el-form-item>
        <el-form-item label="品牌" prop="brand">
          <el-input v-model="form.brand" :disabled="true"/>
        </el-form-item>
        <el-form-item label="wbs" prop="wbs">
          <el-input v-model="form.wbs" :disabled="true"/>
        </el-form-item>
        <el-form-item label="单价(元)" prop="unitPrice">
          <el-input v-model="form.unitPrice" :disabled="true"/>
        </el-form-item>
        <el-form-item label="总库数量" prop="currentNumber">
          <el-input v-model="form.currentNumber" :disabled="true"/>
        </el-form-item>
        <el-form-item label="锁定数量" prop="lockNumber">
          <el-input v-model="form.lockNumber" :disabled="true"/>
        </el-form-item>
        <el-form-item label="当前可用数量">
          <el-input v-model="this.surPlusNum" :disabled="true"/>
        </el-form-item>
        <el-form-item label="出库数量" prop="operNumber">
          <el-input v-model.number="form.operNumber" type="number" min="0"
                    onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
        </el-form-item>
        <el-form-item label="金额" prop="allPrice">
          <el-input v-model="allPrice" :disabled="true"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    修改出库对话框-->
    <el-dialog ref="mydialog" :title="title" :visible.sync="modificationOpen" width="600px" append-to-body>
      <el-form ref="form" :model="modificationform" label-width="120px">
        <el-form-item label="仓库">
          <el-input v-model.number="modificationform.depotName" disabled/>
        </el-form-item>
        <el-form-item label="出库物品" >
          <el-input v-model.number="modificationform.inventoryName" disabled/>
        </el-form-item>
        <el-form-item label="项目代号" >
          <!--          <el-input v-model="form.inventoryId" placeholder="请输入商品Id" />-->
<!--          <el-input v-model.number="modificationform.headerId" disabled/>-->
          <el-select v-model="modificationform.tenantId" placeholder="请选择项目" filterable clearable :disabled="modificationform.tenantId !== '' && modificationform.tenantId !== null" >
            <el-option
              v-for="item in linkHeadOptions"
              :key="item.id"
              :label="item.projectCode"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总库数量">
          <el-input v-model.number="modificationform.currentNumber" disabled/>
        </el-form-item>

        <el-form-item label="锁定数量" prop="lockNumber">
          <el-input v-model="lockNumber" :disabled="true"/>
        </el-form-item>
        <el-form-item label="当前可用数量">
          <el-input v-model="this.surPlusNum" :disabled="true"/>
        </el-form-item>
        <el-form-item label="出库数量">
          <el-input v-model.number="modificationform.operNumber" disabled/>
        </el-form-item>
        <el-form-item label="修改后出库数量">
          <el-input v-model="modificationform.afterNum" type="number" @blur="verify" />
        </el-form-item>
        <el-form-item label="金额(元)">
          <el-input v-model="modificationform.allPrice" disabled=""/>
        </el-form-item>
        <el-form-item label="修改后金额(元)">
          <el-input v-model.number="modificationform.afterMoney" type="number" min="0"
                    onkeyup="this.value=this.value.replace(/[^\d.]/g,'');" />
        </el-form-item>
        <el-form-item label="出库时间">
          <el-date-picker clearable disabled
                          v-model="modificationform.operTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择入库时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="modificationform.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="modificationSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listOutRyDepotItem, getOutRyDepotItem, delOutRyDepotItem, addOutRyDepotItem, updateOutRyDepotItem } from "@/api/warehouse/OutRyDepotItem";
import { allRyDepot } from "@/api/warehouse/RyDepot";
import {allRyInventory, getInventoryInFor, getRyInventory} from "@/api/inventory/RyInventory";
import {floatAdd, floatSub, floatMul,floatDiv} from "@/utils/mathOperate";
import {getInfoByDepotInventoryId, getInventoryByDepotId} from "@/api/warehouse/WareCurrentStock";
import {getLockNumById} from "@/api/warehouse/RyDepotItem";
import request from "../../../utils/request";

export default {
  name: "OutRyDepotItem",
  dicts: ['ware_depot_item_type', 'ware_lock_status'],
  data() {
    return {
      allPrice: null,
      lockNumber : null,
      surPlusNum : null,
      //所有仓库
      allDepot: [],
      allDepot1: [],
      //所有物品
      allInventory: [],
      //搜索框所有物品信息
      selectAllInventory: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 借出表格数据
      OutRyDepotItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 修改的弹出层
      modificationOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        inventoryId: null,
        depotId: null,
      },
      //仓库中物品信息查询参数
      params:{
        depotId:null,
        inventoryId:null,
      },
      // 表单参数
      form: {},
      // 项目代号下拉数组
      linkHeadOptions: [],
      // 修改的表单
      modificationform: {},
      // 表单校验
      rules: {
        depotId: [
          { required: true, message: "仓库不能为空", trigger: "blur" }
        ],
        inventoryId: [
          { required: true, message: "商品不能为空", trigger: "blur" }
        ],
        operNumber: [
          { required: true, message: "出库数量不能为空", trigger: "blur" },
          { type: "number", message: "出库数量只能为数字类型", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    //查询仓库列表
    this.findAllRyDepot();
    //搜素框所有物品
    this.selectAllRyInventory();
    // 获取全部项目代号
    this.getLinkHeadOptions();
  },
  methods: {
    //比较当前数量和锁定数量
    compareNum(){
      if(this.form.operNumber){
        if(this.form.lockNumber){//判断是否存在锁定数量
         // console.log("锁定数量存在！");
          let num = this.form.currentNumber - this.form.lockNumber;
          if(this.form.operNumber > num){
            this.$message({
              message: '警告，出库数量不能大于仓库物品当前可用数量！',
              type: 'warning'
            });
            this.form.operNumber = null;
            this.allPrice = null;
            this.form.allPrice = null;
          } else {//计算总价
            this.sumTotalPrice();
          }

        } else {
         // console.log("锁定数量不存在！");
          if(this.form.operNumber > this.form.currentNumber){
            this.$message({
              message: '警告，出库数量不能大于仓库物品当前可用数量！',
              type: 'warning'
            });
            this.form.operNumber = null;
            this.allPrice = null;
            this.form.allPrice = null;
          } else{//计算总价
            this.sumTotalPrice();
          }
        }
      }
    },

    /**两数相乘*/
    sumTotalPrice() {
     // console.log("SumTotalPrice");
      if (this.form.operNumber && this.form.unitPrice) {
        // this.form.allPrice = this.form.operNumber * this.form.unitPrice;
        this.allPrice = floatMul(this.form.operNumber, this.form.unitPrice);
        this.form.allPrice = this.allPrice;

        // this.form = this.form;
       // console.log(this.form.allPrice.toString());
        // alert("123");

      } else {
        this.form.allPrice = null;
       // console.log("else");
      }
    },

    //根据仓库id和物品id查询仓库中此物品基本信息和当前数量/锁定数量
    onSelectedInventory(val){//这里的val是物品id
      let that = this
     // console.log("params: " +  val + " | " + this.form.depotId);
      this.params.depotId = this.form.depotId;
      this.params.inventoryId = val;
      //根据仓库id和物品id查询仓库中此物品基本信息和当前数量
      getInfoByDepotInventoryId(this.params).then(response => {
        let resultData = {
          depotId : this.form.depotId,
          inventoryId : this.form.inventoryId,
          specifications : response.data.specifications,
          brand : response.data.brand,
          wbs : response.data.wbs,
          currentNumber:response.data.currentNumber,
          unitPrice : response.data.unitPrice,
          lockNumber : null,
          operNumber : null,
          surPlusNum: null
        };

        this.form = resultData;
        //查询锁定数量
        this.getLockNum(this.form.depotId,val)
      });

    },
    // 查询锁定数量
    getLockNum(depotId,val){
      // console.log(this.form)
      this.params.depotId = depotId;
      this.params.inventoryId = val;
      console.log(this.params)
      getLockNumById(this.params).then(response => {
        //锁定数量清空
        this.lockNumber = null;
        this.surPlusNum = null;
        // console.log("--->"+response.data);
        if(typeof(response.data) != "undefined"){
          this.lockNumber = response.data.operNumber;
          this.form.lockNumber =  this.lockNumber;
          this.modificationform.lockNumber =  this.lockNumber;
          // console.log(this.form.lockNumber)

          // console.log("locaNum:" + this.form.lockNumber);
        }else{
          console.log('zxl')
          this.lockNumber = 0
          this.form.lockNumber = 0
          this.modificationform.lockNumber = 0
        }
        this.getSurPlusNum()
      });
    },
// 计算当前可用数量
    getSurPlusNum(){
      if (this.title === '修改出库'){
        this.surPlusNum = eval(this.modificationform.currentNumber) - eval(this.modificationform.lockNumber);
        this.modificationform.surPlusNum = this.surPlusNum
        console.log('修改' + this.modificationform.surPlusNum )
      }else{
      this.surPlusNum = eval(this.form.currentNumber) - eval(this.form.lockNumber);
        this.form.surPlusNum = this.surPlusNum
        console.log('新增' + this.form.surPlusNum )
      }
    },
    //查询仓库列表
    findAllRyDepot(){
      let that = this
      allRyDepot().then(response => {
        //需要将工具库移除

        for (let i = 0; i < response.data.length; i++) {
          if(response.data[i].type !== '2'){
            this.allDepot.push(response.data[i])
           // console.log(that.allDepot)
          }
        }
        that.allDepot1 = response.data

        // let depotArr = response.data;



        //需要移除的数组下标
        // let revIndex = null;
        // for(var i = 0;i < depotArr.length;i++){
        //   //// console.log(depotArr[i].id);
        //   if(depotArr[i].id==2){//id为2的仓库为工具库
        //     revIndex = i;
        //   }
        // }
        // depotArr.splice(revIndex,1);//删除工具库
        // this.allDepot = depotArr;
      });
    },

    //根据仓库id查询仓库中物品列表
    onSelectallRyInventory(val){
      //清空出库物品信息
      this.form.inventoryId = null;
      this.form.specifications = null;
      this.form.brand = null;
      this.form.wbs = null;
      this.form.currentNumber = null;
      this.form.unitPrice = null;
      this.form.lockNumber = null;
      this.form.operNumber = null;
      this.form.allPrice = null;
      this.form.remark = null;
      this.allPrice = null;
      this.lockNumber = null;

      let depotId = val;//仓库id
      getInventoryByDepotId(depotId).then(response => {
        this.allInventory = response.data;
      });
    },


    //搜素框所有物品列表
    selectAllRyInventory(){
      allRyInventory().then(response => {
        this.selectAllInventory = response.data;
      });
    },

    /** 查询借出列表 */
    getList() {
      this.loading = true;
      listOutRyDepotItem(this.queryParams).then(response => {
        this.OutRyDepotItemList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.modificationOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.allPrice=null;
      this.lockNumber=null;
      this.form = {
        id: null,
        headerId: null,
        inventoryId: null,
        operNumber: null,
        allPrice: null,
        specifications:null,
        brand:null,
        wbs:null,
        unitPrice:null,
        currentNumber:null,
        lockNumber:null,
        remark: null,
        depotId: null,
        anotherDepotId: null,
        headerType: null,
        lockStatus: "0",
        taxRate: null,
        taxMoney: null,
        taxLastMoney: null,
        snList: null,
        batchNumber: null,
        expirationDate: null,
        linkId: null,
        tenantId: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      // this.title = "添加借出";
      this.title = "添加出库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      let id = row.id || this.ids

      id = typeof id === "object" ? id[0] : id
      this.modificationOpen = true;
      for (let i = 0; i < this.OutRyDepotItemList.length; i++) {
        if (this.OutRyDepotItemList[i].id === id) {
          this.title = "修改出库";
          this.modificationform = this.OutRyDepotItemList[i]
          // this.modificationform.afterNum = null
          this.getLockNum(this.modificationform.depotId,this.modificationform.inventoryId)
        }

      }
          console.log(this.modificationform)
     // this.modificationform.afterNum = null
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.projectId = this.form.projectCode
            alert("projectCode="+this.form.projectCode)
            alert("projectId="+this.form.projectId)
            updateOutRyDepotItem(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            if (this.form.operNumber <= 0 || this.form.operNumber === undefined) {
              this.$modal.msgWarning("出库数量不能0或负数");
            }else if(this.form.operNumber > this.surPlusNum){
              this.$modal.msgWarning("出库数量大于可用数量");
            } else {
              addOutRyDepotItem(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    verify(){
      if (this.modificationform.afterNum > this.surPlusNum + this.modificationform.operNumber){
        this.$modal.msgWarning("出库数量超出可用数量");
      } else if(this.modificationform.afterNum <= 0){
        this.modificationform.afterNum = ''
        this.$modal.msgWarning("出库数量不能为0或负数");
      }
    },
    /*修改的提交按钮*/
    modificationSubmitForm() {
     console.log(this.modificationform.afterNum)
      if (this.modificationform.afterNum > this.surPlusNum + this.modificationform.operNumber){
        this.$modal.msgWarning("出库数量超出可用数量");
      }else if (this.modificationform.afterNum <= 0 && this.modificationform.afterNum !== ''){
        console.log('执行了')
        this.$modal.msgWarning("出库数量不能为0或负数");
      }else{
      this.modificationform.beforeNum = this.modificationform.operNumber;
      this.modificationform.beforeMoney = this.modificationform.allPrice;
      this.modificationform.depotitemId = this.modificationform.id;
      this.modificationform.projectId = this.modificationform.tenantId;

      updateOutRyDepotItem(this.modificationform).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.modificationOpen = false;
        this.getList();
      });
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除借出编号为"' + ids + '"的数据项？').then(function() {
        return delOutRyDepotItem(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('warehouse/OutRyDepotItem/export', {
        ...this.queryParams
      }, `OutRyDepotItem_${new Date().getTime()}.xlsx`)
    },
    // 查询所有项目代号
    getLinkHeadOptions(){
      let that = this
      return request({
        url: '/purchase/ryDepotHead/all',
        method: 'get'
      }).then(function (res) {
       // console.log('res')
       // console.log(res)
         that.linkHeadOptions = res.data
        // that.organOptions = ress.data
      })
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}
input[type="number"] {
  -moz-appearance: textfield;
}
</style>
